package com.authorization.authorizationserveronsso.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author ：hyq
 * @date ：Created in 2020/12/30 9:03
 * @description：
 * @modified By：
 */
public class MD5Encrypt {
    private static String encryptedString;

    private MD5Encrypt() {
    }

    public static String encrypt(String string) {
        encryptedString = encryptString(string);
        return encryptedString;
    }

    public static boolean compareEncrypted(String string) {
        return encryptedString != null && encryptedString.equals(encryptString(string));
    }

    public static boolean compareEncrypted(String crypt, String string) {
        return crypt != null && crypt.equals(encryptString(string));
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";

        for(int n = 0; n < b.length; ++n) {
            stmp = Integer.toHexString(b[n] & 255);
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }

        return hs.toUpperCase();
    }

    public static byte[] hex2byte(String b) {
        byte[] bb = new byte[b.length() / 2];
        int n = 0;

        for(int i = 0; n < b.length(); n += 2) {
            bb[i] = (byte)(Integer.parseInt(b.substring(n, n + 2), 16) & 255);
            ++i;
        }

        return bb;
    }

    public static String encryptString(String str) {
        if (str != null && str.length() != 0) {
            byte[] val = str.getBytes();
            MessageDigest algorithm = null;

            try {
                algorithm = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException var5) {
                return null;
            }

            algorithm.reset();
            algorithm.update(val);
            byte[] digest = algorithm.digest();
            String crypt = byte2hex(digest);
            return crypt;
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println(encryptString("123456"));
    }

}
